package com.lc.lucene.index;

import java.io.File;
import java.io.IOException;
import java.util.List;

import org.apache.lucene.analysis.WhitespaceAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.index.CorruptIndexException;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.LockObtainFailedException;
import org.apache.lucene.store.SimpleFSDirectory;
import org.apache.lucene.store.SimpleFSLockFactory;

import com.lc.lucene.entry.Program;

public class LuceneIndex {
	
	private static final String PATH = "D:\\index";
	
	private List<Program> programDocuments;
	
	public LuceneIndex(List<Program> programDocuments){
		this.programDocuments = programDocuments;
	}
	
	public void createIndex(){
		try {
			Directory directory = new SimpleFSDirectory(new File(PATH),new SimpleFSLockFactory());
			IndexWriter write = new IndexWriter(directory,new WhitespaceAnalyzer(),true,IndexWriter.MaxFieldLength.UNLIMITED);
			write.setUseCompoundFile(false);
			for(Program program:programDocuments){
				Document doc = new Document();
				Field fd = new Field("name",program.getName()==null?"abc":program.getName(),Field.Store.YES,Field.Index.ANALYZED);
				doc.add(fd);
				fd = new Field("url",program.getUrl(),Field.Store.YES,Field.Index.ANALYZED);
				doc.add(fd);
				write.addDocument(doc);
			}
			write.close();
		} catch (CorruptIndexException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (LockObtainFailedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}
